package jp.co.cos.ittrick.channel.controller.channel;

import java.util.List;

import jp.co.cos.ittrick.channel.Constants;
import jp.co.cos.ittrick.channel.model.ApplicationModel;
import jp.co.cos.ittrick.channel.model.CategoryModel;
import jp.co.cos.ittrick.channel.model.ChannelModel;
import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.service.ApplicationService;
import jp.co.cos.ittrick.channel.service.ChannelService;
import jp.co.cos.ittrick.channel.service.ChapterService;
import jp.co.cos.ittrick.channel.service.PageService;
import jp.co.cos.ittrick.channel.util.Utility;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Text;

public class ChapterController extends Controller {

    private ApplicationService applicationService;
    private ChannelService channelService;
    private ChapterService chapterService;
    private PageService pageService;
    private ApplicationModel applicationModel;
    private ChapterModel chapterModel;
    private ChannelModel channelModel;

    public ChapterController() {
        chapterService = new ChapterService();
        channelService = new ChannelService();
        applicationService = new ApplicationService();
        pageService = new PageService();
    }

    @Override
    public Navigation run() throws Exception {

        applicationModel = applicationService.getApplicationModel();
        requestScope("applicationModel", applicationModel);

        String channel = asString("channel");
        String chapter = asString("chapter");

        try {
            channelModel = channelService.getChannelByKey(channel);
            requestScope("channelModel", channelModel);
        }catch(Exception e) {
            return forward("/exception/exception404");
        }

        try {
            chapterModel = chapterService.getChapterByKey(Integer.valueOf(chapter));
            changeImage();
            requestScope("chapterModel", chapterModel);
        }catch(Exception e) {
            return forward("/exception/exception404");
        }

        try {
            CategoryModel categoryModel = chapterModel.getCategoryModelRef().getModel();
            requestScope("categoryModel", categoryModel);
        }catch(Exception e) {
            return forward("/exception/exception404");
        }

        if(channelModel == null || chapterModel == null) {
            return forward("/exception/exception404");
        }

        String thisPageUrl = "http://" + applicationModel.getApplicationId() + ".appspot.com/" + channelModel.getKeyString() + "/c" + chapterModel.getKeyString() + ".html";
        requestScope("thisPageUrl", thisPageUrl);

        // new 記事
        List<PageModel> newPageList = pageService.getPageListOfLimit(0, Constants.PAGE_ARTICLE_LIST_LIMIT);
        requestScope("newPageList", newPageList);

        // チャンネルリスト
        List<ChannelModel> channelList = channelService.getAll();
        requestScope("channelList", channelList);


        // スマートフォンの場合
        if(Utility.isSmartPhone(request)) {
            return forward("/sp/channel/chapter.jsp");
        }

        return forward("chapter.jsp");
    }

    private void changeImage() {

        StringBuffer contentNew = new StringBuffer("");
        String contentOld = chapterModel.getContentString();

        String[] spList = contentOld.split("##");
        for(String tmp: spList) {

            // すべてを対象に数字に変換する。
            // ID以外の部分はエラーになるので無視する
            try {

                String imageName = "";
                String imagePass = "";

                String[] splitName = tmp.split("\\.");
                if(splitName.length == 2) {
                    if(splitName[1].equals("jpg") || splitName[1].equals("png") || splitName[1].equals("gif")) {
                        imageName = tmp;

                        imagePass = Constants.IMAGE_PATH_BASE_URL +
                        applicationModel.getApplicationId() +
                        "/images/" +
                        channelModel.getKeyString() +
                        "/" +
                        chapterModel.getKeyString() +
                        "/" +
                        imageName;

                    }
                }

                // preを挿入する
                if(!imagePass.equals("")) {
                    contentNew.append("<img src=\"" + imagePass + "\"/>");

                    // 数字であるが、該当preModelが存在しない場合は、
                    // そのまんま挿入
                }else {
                    contentNew.append(tmp);
                }

                // エラーになった場合はpreId以外のコンテンツであるため、
                // そのまんま挿入
            }catch (Exception e) {
                contentNew.append(tmp);
            }

        }

        chapterModel.setContent(new Text(contentNew.toString()));

    }
}
